package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AjaxAuthenticationFilter extends FormAuthenticationFilter {
    //写这个类主要是为了继承父类的并且覆盖父类登录成功或者失败之后响应json数据回到页面


    //登录成功
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        JsonResult result = new JsonResult(true, "登录成功");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result));
        return false;
    }

    //登录失败
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        JsonResult result = new JsonResult();
        result.setSuccess(false);
        PrintWriter writer = null;

        if(e instanceof UnknownAccountException){
            result.setMsg("用户名错误");
        }else if(e instanceof IncorrectCredentialsException){
            result.setMsg("密码错误");
        }else{
            result.setMsg("未知错误");
        }
        try {
            writer = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        writer.write(JSON.toJSONString(result));
        return false;
    }
}
